<template>
    <view class="layout-classify" :style="{ height: `${props.height}px` }">
        <!-- 头部大分类 -->
        <view class="big-classify">
            <view class="scroll-view-box">
                <scroll-view class="scroll-view" enable-flex :scroll-x="true" :scroll-left="state.topScrollLeft"
                    :scroll-with-animation="true" :show-scrollbar="false">
                    <view :class="['item', { 'on': state.topTabId === item.id }]"
                        v-for="item, index in state.classifyData" :key="index" @click="hanldeChangeTopTab(item, index)">
                        <view class="img-box">
                            <image class="img" :src="item.imageUrl"></image>
                        </view>
                        <view>
                            <text class="tit">{{ item.name }}</text>
                        </view>
                    </view>
                </scroll-view>
            </view>
            <view class="all-big-classify" @click="hanldeShowBigClassifyPop">
                <text class="tit">全部</text>
                <image class="img" :src="handleStaticResources('/static/images/icon/all-drop-down.png')"></image>
            </view>
        </view>

        <view class="classify-box" :style="{ height: `${props.height - state.bigClassifyH}px` }">
            <view class="classify-left">
                <scroll-view class="scroll-view" enable-flex :scroll-y="true">
                    <view :class="['item', { 'on': state.leftTabId === item.id }]"
                        v-for="item, index in state.leftTabList" :key="index" @click="hanldeChangeLeftTab(item)">
                        {{ item.name }}
                    </view>
                    <view class="no-more"></view>
                </scroll-view>
            </view>
            <view class="classify-right">
                <view class="right-tab-box">
                    <view>
                        <coreshop-tabs :list="state.rightTabList"
                            @hanldeClickTab="hanldeChangeRightTab"></coreshop-tabs>
                    </view>
                </view>
                <scroll-view class="scroll-view" enable-flex
                    :style="{ 'height': `${props.height - state.bigClassifyH - state.rightTabH}px` }" :scroll-y="true"
                    @scrolltolower="handleScrolltolower">
                    <view class="advert-box radius-15">
                        <coreshop-advert :code="advertPosition.goodsClassifyBanner"></coreshop-advert>
                    </view>
                    <view class="data-box" v-if="state.goodsList.length > 0">
                        <view class="item-box" v-for="item in state.goodsList" :key="item.id">
                            <coreshop-goods-card imgWidth="150rpx" imgHeight="150rpx"
                                :goodsData="hanldeCombinationGoodsData(item)" @hanldeClickGoods="hanldeClickGoods">
                                <template #goodPrice>
                                    <view class="price-msg">
                                        <view class="price-box">
                                            <view class="price">
                                                <text class="symbol">￥</text>
                                                <text class="num">{{ item.price }}</text>
                                            </view>
                                            <view class="underlin-price">￥{{ item.mktprice }}</view>
                                        </view>
                                        <view class="btn" @click="handleSelectSku(item.id)">
                                            <image class="img" :src="handleStaticResources('/static/images/cart.png')">
                                            </image>
                                        </view>
                                    </view>
                                </template>
                            </coreshop-goods-card>
                        </view>
                        <view class="no-more">
                            <uv-divider :dashed="true"
                                :text="state.totalPages > state.page ? '下滑加载更多' : '没有更多了'"></uv-divider>
                        </view>
                    </view>
                    <view v-else>
                        <coreshop-empty></coreshop-empty>
                    </view>
                </scroll-view>
            </view>
        </view>

        <!-- 购物车盒子 -->
        <view class="shopping-box">
            <view class="shopping-Bag">
                <view class="bag-box">
                    <image class="img" :src="handleStaticResources('/static/images/cart-bag.png')"></image>
                </view>
                <view class="price-box">
                    <text class="num">购物车数量:{{ props.cartData.count }}</text>
                    <text class="price">￥{{ props.cartData.money }}</text>
                </view>
            </view>
            <view class="btn-buy" @click="handleGoPay">
                去结算
            </view>
        </view>

        <!-- 商品sku弹框 -->
        <GoodsDetailSkuPopup :showSku="state.showSku" :goodsDetailData="state.goodsDetailData"
            :safeAreaInsetBottom="false" :buyNowNowloading="buyNowLoading" :addCartloading="addCartLoading"
            @handleChangePopup="handleChangePopup" @handleAddCart="handleAddCart" @handleBuyNow="handleBuyNow">
        </GoodsDetailSkuPopup>

        <!-- 头部大分类的弹框 -->
        <uv-popup ref="bigClassifyPop" mode="top" :safeAreaInsetBottom="false">
            <view class="big-classify-pop" :style="{ 'padding-top': `${props.statusBarHeight}px` }">
                <view class="title">全部分类</view>
                <view class="item-box">
                    <view :class="['item', { 'on': state.topTabId === item.id }]"
                        v-for="item, index in state.classifyData" :key="index" @click="hanldeChangeTopTab(item, index)">
                        <view class="img-box">
                            <image class="img" :src="item.imageUrl"></image>
                        </view>
                        <view>
                            <text class="tit">{{ item.name }}</text>
                        </view>
                    </view>
                </view>
                <view class="put-away" @click="hanlderHidebigClassifyPop">点击收起<uv-icon name="arrow-up" size="15px"
                        color="6E737D"></uv-icon></view>
            </view>
        </uv-popup>
    </view>
</template>

<script setup lang="ts">
    import { reactive, watch, ref, onMounted, getCurrentInstance, nextTick } from 'vue';
    import { advertPosition, UserToken, onClassifyPageHide, onClassifyPagePullDownRefresh } from '@/core/consts';
    import { useLoginStore } from '@/core/store';
    import { queryGoodsPageList, queryGoodsDetailByToken, queryGoodsDetail, queryAddCart } from '@/core/api';
    import type { CategoriesType, Response, GoodsListType, GoodsType, CartMoneyNumType } from '@/core/models';
    import { getDomInfo, handleStaticResources, handleRouteNavigateTo, handleShowToast, handleRouteSwitchTab } from '@/core/utils';
    import { AddCartEnum, PaymentTypeEnum, RouteSwitchTabEnum } from '@/core/enum';
    import GoodsDetailSkuPopup from '@/pages/components/goods-detail/components/goods-detail-sku/goods-detail-sku.vue';
    import { useLoadingFn } from '@/core/hooks';

    const instance = getCurrentInstance();

    /** 登录store */
    const _useLoginStore = useLoginStore();

    const props = withDefaults(defineProps<{
        data : Array<CategoriesType>,
        height : number,
        statusBarHeight : number,
        cartData : CartMoneyNumType,
    }>(), {
        data: () => [],
        height: 0,
        statusBarHeight: 0,
        cartData: () => ({}),
    });

    const bigClassifyPop = ref();

    const state = reactive<{
        classifyData : Array<CategoriesType>;
        topTabId : number;
        topScrollLeft : number;
        leftTabId : number;
        leftTabList : Array<CategoriesType>;
        rightTabList : Array<CategoriesType>;
        catId : number;
        goodsList : Array<GoodsType>;
        page : number;
        totalPages : number;
        bigClassifyH : number; // 大分类盒子的高度
        rightTabH : number; // 右侧tab盒子的高度
        cartCount : number;
        cartMoney : number,
        showSku : boolean;
        goodsDetailData : any;
        selectGoodsId : number;
    }>({
        classifyData: [],
        topTabId: 0,
        topScrollLeft: 0,
        leftTabId: 0,
        leftTabList: [],
        rightTabList: [],
        catId: 0,
        goodsList: [],
        page: 1,
        totalPages: 0,
        bigClassifyH: 0,
        rightTabH: 0,
        cartCount: 0,
        cartMoney: 0,
        showSku: false,
        goodsDetailData: {},
        selectGoodsId: 0,
    });

    const buyNowLoading = ref(false);
    const addCartLoading = ref(false);

    const handleBuyNow = useLoadingFn(onBuyNow, buyNowLoading);
    const handleAddCart = useLoadingFn(onAddCart, addCartLoading)

    const emit = defineEmits(['getCartNumAndMoney'])

    watch(() => props.data, (newVal : Array<CategoriesType>) => {
        if (newVal) {
            state.classifyData = newVal.map((item : CategoriesType) => {
                item.child.forEach((cell : CategoriesType) => {
                    cell.child.unshift({
                        name: "全部",
                        id: cell.id,
                    })
                })
                return item;
            });

            state.topTabId = state.classifyData[0]?.id;
            state.leftTabId = state.classifyData[0]?.child[0]?.id;
            state.leftTabList = state.classifyData[0]?.child;
            state.rightTabList = state.classifyData[0]?.child[0]?.child;

            state.catId = state.classifyData[0]?.child[0]?.id;
            getGoodsPageList();
        }
    })

    onMounted(() => {
        uni.$on(onClassifyPageHide, () => {
            state.showSku = false;
        })

        uni.$on(onClassifyPagePullDownRefresh, () => {
            state.page = 1;
            state.totalPages = 1;
            state.goodsList = [];
        })

        nextTick(async () => {
            state.bigClassifyH = ((await getDomInfo('.big-classify', instance.proxy)) as { height : number }).height;
            setTimeout(async () => {
                state.rightTabH = ((await getDomInfo('.right-tab-box', instance.proxy)) as { height : number }).height;
            }, 100)
        })
    })

    // 获取商品列表数据
    const getGoodsPageList = async () => {
        if (!state.catId) { return; }
        const goodsPageList : Response<GoodsListType> = await queryGoodsPageList({
            page: state.page,
            limit: 10,
            where: `{"catId":${state.catId}}`
        });
        if (goodsPageList.status) {
            state.totalPages = goodsPageList.data?.totalPages;
            state.goodsList = state.goodsList.concat(goodsPageList.data?.list);
        }
    }

    /** 选择sku */
    const handleSelectSku = (id : number) => {
        if (state.selectGoodsId == id) {
            state.showSku = true;
            return;
        }
        _useLoginStore.checkLogin(async () => {
            let goodsDetail : any = null;
            if (uni.getStorageSync(UserToken)) {
                goodsDetail = await queryGoodsDetailByToken({
                    id: id,
                    data: true,
                })
            } else {
                goodsDetail = await queryGoodsDetail({
                    id: id,
                    data: true,
                })
            }
            state.goodsDetailData = goodsDetail.data;
            state.showSku = true;
        });
    }

    /** 底部按钮去结算 */
    const handleGoPay = () => {
        _useLoginStore.checkLogin(() => {
            handleRouteSwitchTab(RouteSwitchTabEnum.cart);
        });
    }

    /** 添加购物车 */
    async function onAddCart({ productId, nums } : any) {
        const addCart : Response<number> = await queryAddCart({
            productId,
            nums,
            type: AddCartEnum.add,
        });
        if (addCart.status) {
            handleShowToast(addCart.msg, "success");
            /** 添加成功后，重新获取购物车数量和价格 */
            emit("getCartNumAndMoney");
            /** 关闭sku弹框 */
            handleChangePopup(false);
        } else {
            handleShowToast(addCart.msg);
        }
    }

    /** 立即购买 */
    async function onBuyNow({ productId, nums } : any) {
        const addCart : Response<number> = await queryAddCart({
            productId,
            nums,
            type: AddCartEnum.buy,
            cartType: PaymentTypeEnum.common,
        });
        if (addCart.status) {
            handleRouteNavigateTo(`/pages/order/submit/submit?cartIds=${addCart.data}`)
            /** 关闭sku弹框 */
            handleChangePopup(false);
        } else {
            handleShowToast(addCart.msg);
        }
    }

    /** sku弹框显示隐藏 */
    const handleChangePopup = (show : boolean) => {
        state.showSku = show;
    }

    /** 切换顶部tab */
    const hanldeChangeTopTab = (item : CategoriesType, index : number) => {
        if (state.leftTabId != item.id) {
            calculationTopMovingDistance(index);
            state.topTabId = item.id;
            state.catId = item.id;

            state.leftTabId = item?.child[0].id;
            state.leftTabList = item?.child;
            state.rightTabList = item?.child[0]?.child;

            handleResetGoodsList();
            hanlderHidebigClassifyPop();
        }
    }

    /** 显示顶部大分类弹框 */
    const hanldeShowBigClassifyPop = () => {
        bigClassifyPop.value.open();
    }
    /** 隐藏顶部大分类弹框 */
    const hanlderHidebigClassifyPop = () => {
        bigClassifyPop.value.close();
    }

    /** 计算顶部tab移动的距离 */
    const calculationTopMovingDistance = (index : number) => {
        let topScrollLeft = 0;
        for (let i = 0; i < index - 1; i++) {
            topScrollLeft += 60
        };
        state.topScrollLeft = topScrollLeft
    }

    /** 切换左侧tab */
    const hanldeChangeLeftTab = (item : CategoriesType) => {
        if (state.leftTabId != item.id) {
            state.leftTabId = item.id;
            state.catId = item.id;
            state.rightTabList = item?.child;
            handleResetGoodsList();
        }
    }

    /** 切换右侧tab */
    const hanldeChangeRightTab = (item : CategoriesType) => {
        state.catId = item.id;
        handleResetGoodsList();
    }

    /** 组合商品数据传入组件 */
    const hanldeCombinationGoodsData = (item : GoodsType) => {
        return {
            id: item.id,
            image: item.image,
            name: item.name,
            brief: item.brief,
            price: item.price,
            mktprice: item.mktprice,
            isRecommend: item.isRecommend,
            isHot: item.isHot,
        }
    }

    const hanldeClickGoods = (item : GoodsType) => {
        uni.navigateTo({
            url: `/pages/goods/detail?id=${item.id}`
        })
    }

    /** 加载下一页数据 */
    const handleScrolltolower = () => {
        if (state.totalPages > state.page) {
            state.page++;
            getGoodsPageList();
        }
    }

    /** 重置商品列表数据 */
    const handleResetGoodsList = () => {
        state.page = 1;
        state.goodsList = [];
        getGoodsPageList();
    }
</script>

<style lang="scss" scoped>
    @import './classify-five.scss';
</style>